package com.a01_2021.thousandstimes.saas.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.saas.entity.UserMapping;
import com.a01_2021.thousandstimes.saas.mapper.UserMappingMapper;
import com.a01_2021.thousandstimes.saas.service.IUserMappingService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-03-24
 */
@Service
public class UserMappingServiceImpl extends ServiceImpl<UserMappingMapper, UserMapping> implements IUserMappingService {

    @Resource
    UserMappingMapper userMappingMapper;

    /**
     * 通过用户名查询其映射表
     *
     * @param username 用户名
     * @return userMapping实体类（当映射不存在时返还null对象
     */
    @Override
    @DS("master")
    public UserMapping getUserMapping(String username) {
        QueryWrapper<UserMapping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMappingMapper.selectOne(queryWrapper);
    }

    /**
     * 用于添加映射
     *
     * @param username   用户名
     * @param instanceId 用户id
     * @return userMapping实体类
     */
    @DS("master")
    public UserMapping addUserMapping(String username, long instanceId) {
        UserMapping userMapping = this.getUserMapping(username);
        if (userMapping != null) {
            //若已经存在映射
            userMapping.setInstanceId(instanceId);
            userMappingMapper.updateById(userMapping);
        } else {
            //若不存在映射
            userMapping = new UserMapping(null, username, instanceId);
            userMappingMapper.insert(userMapping);
        }
        return userMapping;
    }

    /**
     * 用于删除用户映射
     *
     * @param username   用户名
     * @param instanceId 实例id
     * @return 返还是否删除成功
     * @throws CustomException 当用户映射与实例id不符时抛出该异常
     */
    @DS("master")
    public boolean deleteUserMapping(String username, long instanceId) throws CustomException {
        UserMapping userMapping = this.getUserMapping(username);
        if (userMapping == null) {
            //不存在映射
            return false;
        }
        if (userMapping.getInstanceId() != instanceId) {
            //映射不属于该实例
            throw new CustomException(CustomExceptionType.OPERATION_NOT_ALLOW, "不允许删除其他实例的用户映射");
        }
        userMappingMapper.deleteById(userMapping);
        return true;
    }
}
